package com.example.demo.heima.bio;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname BioServer
 * @description
 * @date 2023/07/16 10:14
 * <p>
 * ******************************************************
 */
public class BioServer {

    public static void main(String[] args) throws IOException {
        // 基于ServerSocket
        ServerSocket serverSocket = new ServerSocket(8888);

        System.out.println("服务器绑定端口，开启监听");

        while (true) {
            // 获取一个客户端连接，accept是阻塞的
            Socket socket = serverSocket.accept();
            new Thread(new SocketHandle(socket)).start();
        }
    }


    static public class SocketHandle implements Runnable {

        private final Socket socket;

        public SocketHandle(Socket socket) {
            this.socket = socket;
        }


        @Override
        public void run() {
            try {
                // 执行业务代码逻辑
                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();

                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));

                while (true) {
                    final String line = reader.readLine();
                    System.out.println("收到了来自客户端的数据："+line);
                    // bus业务操作

                    //向客户端写数据
                    writer.write("hello bio client, i am bio server\n");
                    writer.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
